package com.witmore.neutron.ai.web.wechat.client;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.wechat.client.dto.StockAbnormalRecordQueryRequest;
import com.witmore.neutron.ai.web.wechat.dto.StockAbnormalRecordDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * MCP股票异动记录服务客户端
 * 负责调用MCP服务的股票异动记录接口
 */
@Slf4j
@Component
public class McpStockAbnormalRecordClient {

    @Value("${spring.ai.mcp.stock-alert.service.base-url:http://localhost:8096}")
    private String mcpServiceBaseUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 分页查询股票异动记录
     */
    public ResponsePageResult<StockAbnormalRecordDTO> queryAbnormalRecords(Long userId, String stockCode, String stockName,
                                                                           Integer abnormalTypeCode, LocalDate startDate, LocalDate endDate,
                                                                           long page, long size) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-abnormal-record/query";

            StockAbnormalRecordQueryRequest request = new StockAbnormalRecordQueryRequest();
            request.setUserId(userId);
            request.setStockCode(stockCode);
            request.setStockName(stockName);
            request.setAbnormalTypeCode(abnormalTypeCode);
            request.setStartDate(startDate);
            request.setEndDate(endDate);
            request.setPage(page);
            request.setSize(size);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<StockAbnormalRecordQueryRequest> entity = new HttpEntity<>(request, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                // 直接解析ResponsePageResult，从data字段获取Page
                String responseBody = response.getBody();
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if (Objects.requireNonNull(jsonObject).getInteger("code") == 200) {
                    List<StockAbnormalRecordDTO> records = JSONArray.parseArray(jsonObject.getString("records"), StockAbnormalRecordDTO.class);
                    PageInfo pageInfo = JSONObject.parseObject(jsonObject.getString("page"), PageInfo.class);
                    return ResponsePageResult.success(records, pageInfo);
                }
                return ResponsePageResult.fail(500, "远程服务调用异常");

            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return ResponsePageResult.fail(500, "远程调用异常");
            }

        } catch (Exception e) {
            log.error("调用MCP服务分页查询异动记录失败: userId={}", userId, e);
            return ResponsePageResult.fail(500, "远程调用异常");
        }
    }

    /**
     * 根据ID获取股票异动记录详情
     */
    public ResponseResult<StockAbnormalRecordDTO> getAbnormalRecordById(Long recordId) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-abnormal-record/get/" + recordId ;

            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                return parseResponseResult(response.getBody());
            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return ResponseResult.fail(500, "远程调用异常");
            }

        } catch (Exception e) {
            log.error("调用MCP服务获取异动记录失败: recordId={}", recordId, e);
            return ResponseResult.fail(500, "远程调用异常");
        }
    }

    /**
     * 获取股票异动预警详情
     */
    public Object getAlertDetail(Integer alertId) {
        try {
            String url = mcpServiceBaseUrl + "/api/stock-abnormal-record/alert-detail/" + alertId;

            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                TypeReference<ResponseResult<Object>> typeRef = new TypeReference<ResponseResult<Object>>() {};
                ResponseResult<Object> result = JSONObject.parseObject(response.getBody(), typeRef);
                if (result != null && result.getCode() == 200 && result.getData() != null) {
                    log.info("MCP服务获取异动预警详情成功: alertId={}", alertId);
                    return result.getData();
                } else {
                    log.warn("MCP服务获取异动预警详情失败: alertId={}, , message={}",
                        alertId,  result != null ? result.getMessage() : "未知错误");
                    return null;
                }
            } else {
                log.warn("MCP服务调用失败: statusCode={}", response.getStatusCode());
                return null;
            }

        } catch (Exception e) {
            log.error("调用MCP服务获取异动预警详情失败: alertId={}", alertId, e);
            return null;
        }
    }



    /**
     * 解析ResponseResult响应
     */
    private ResponseResult<StockAbnormalRecordDTO> parseResponseResult(String responseBody) {
        try {
            TypeReference<ResponseResult<StockAbnormalRecordDTO>> typeRef =
                new TypeReference<ResponseResult<StockAbnormalRecordDTO>>() {};
            ResponseResult<StockAbnormalRecordDTO> result = JSON.parseObject(responseBody, typeRef);

            // 进一步处理DTO，补充计算字段
            if (result != null && result.getData() != null) {
                enhanceStockAbnormalRecordDTO(result.getData());
            }

            return result;
        } catch (Exception e) {
            log.error("解析ResponseResult失败: {}", responseBody, e);
            return null;
        }
    }

    /**
     * 增强StockAbnormalRecordDTO，补充计算字段
     */
    private void enhanceStockAbnormalRecordDTO(StockAbnormalRecordDTO dto) {
        try {
            // 根据涨跌比例计算异动类型编码
            if (dto.getRiseRatio() != null && dto.getRiseRatio().compareTo(BigDecimal.ZERO) > 0) {
                dto.setAbnormalTypeCode(1); // 上涨
                dto.setAbnormalType("上涨");
                dto.setAbnormalRatio(dto.getRiseRatio());
            } else if (dto.getFallRatio() != null && dto.getFallRatio().compareTo(BigDecimal.ZERO) > 0) {
                dto.setAbnormalTypeCode(2); // 下跌
                dto.setAbnormalType("下跌");
                dto.setAbnormalRatio(dto.getFallRatio());
            }

            log.debug("增强DTO字段成功: stockCode={}, abnormalType={}, abnormalRatio={}",
                dto.getStockCode(), dto.getAbnormalType(), dto.getAbnormalRatio());

        } catch (Exception e) {
            log.warn("增强DTO字段失败: stockCode={}", dto.getStockCode(), e);
        }
    }


}
